import android.content.Context;
import android.graphics.Bitmap;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.Switch;
import android.widget.TextView;

public class ViewHolder {
    private final SparseArray<View> mViews;
    private int mPosition;
    private View mConvertView;
    private ViewHolder(Context context, ViewGroup parent, int layoutId,int position)
    {
        this.mPosition = position;
        this.mViews = new SparseArray<View>();
        mConvertView = LayoutInflater.from(context).inflate(layoutId, parent,
                false);
        // setTag
        mConvertView.setTag(this);
    }


    public void setView(int id,Object v){
        View a = getView(id);
        if(a instanceof TextView){
            setTextViewText((TextView)a,(String)v);
        }else if(a instanceof ImageView||v instanceof Integer){
            setImageResource((ImageView)a,(int)v);
        }else if(a instanceof ImageView||v instanceof Bitmap){
            setImageBitmap((ImageView)a,(Bitmap)v);
        }else if(a instanceof CheckBox){
            setChecked((CheckBox)a,(boolean)v);
        }else if(a instanceof RadioButton){
            setChecked((RadioButton) a,(boolean)v);
        }else if(a instanceof Switch){
            setChecked((Switch)a,(boolean)v);
        }
    }


    public static ViewHolder get(Context context, View convertView, ViewGroup parent, int layoutId, int position)
    {
        if (convertView == null)
        {
            return new ViewHolder(context, parent, layoutId, position);
        }
        return (ViewHolder) convertView.getTag();
    }

    public View getConvertView()
    {
        return mConvertView;
    }

    public <T extends View> T getView(int viewId)
    {
        View view = mViews.get(viewId);
        if (view == null)
        {
            view = mConvertView.findViewById(viewId);
            mViews.put(viewId, view);
        }
        return (T) view;
    }


    public void setTextViewText(TextView view, String text)
    {
        view.setText(text);
    }
    public void setImageResource(ImageView view, int drawableId)
    {
        view.setImageResource(drawableId);
    }
    public void setImageBitmap(ImageView view, Bitmap bm)
    {
        view.setImageBitmap(bm);
    }

    public int getPosition()
    {
        return mPosition;
    }


    public void setChecked(CheckBox v, boolean a){
        v.setChecked(a);
    }
    public void setChecked(Switch checked, boolean a){
        checked.setChecked(a);
    }
    public void setChecked(RadioButton v, boolean a){
        v.setChecked(a);
    }

}